package net.cardgame.orcalecard;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.NoSuchPaddingException;

import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.ImageClickable;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.FileUtils;
import net.cardgame.orcalecard.utils.Utils;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

public class CardDetailActivity extends Activity implements OnClickListener {
	private Button btnBack, btnHelp;

	private TextView tv_title;
	private TextView tv_title_jp;

	private WebView tv_content1;
	private WebView tv_content2;
	private WebView tv_content3;

	private ImageClickable iv_card;
	private ImageClickable iv_background;
	private int cardId = 0;
	private int deckId = -1; // Chỉ số ID của bộ bài
	private int indexTypeHelp = 5;
	private String pathImageSmall = "";
	ProgressBar progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.card_detail_activity);
		ScrollView scrollView = (ScrollView) findViewById(R.id.ScrollView01);
		scrollView.setFadingEdgeLength(0);
		progress = (ProgressBar) findViewById(R.id.progressBar);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_title_jp = (TextView) findViewById(R.id.tv_title_jp);

		// WebView
		tv_content1 = (WebView) findViewById(R.id.tv_content1);
		tv_content2 = (WebView) findViewById(R.id.tv_content2);
		tv_content3 = (WebView) findViewById(R.id.tv_content3);

		// Set background cho webview
		tv_content1.setBackgroundColor(0x00000000);
		tv_content2.setBackgroundColor(0x00000000);
		tv_content3.setBackgroundColor(0x00000000);

		// disable copy paste in webview
		tv_content1.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});
		tv_content1.setLongClickable(false);
		tv_content2.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});
		tv_content2.setLongClickable(false);
		tv_content3.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});
		tv_content3.setLongClickable(false);

		btnBack = (Button) findViewById(R.id.btnBack);
		btnHelp = (Button) findViewById(R.id.btnHelp);
		iv_card = (ImageClickable) findViewById(R.id.iv_card);
		iv_background = (ImageClickable) findViewById(R.id.iv_background);
		iv_card.setClickable(false);
		iv_background.setClickable(false);
		Bundle bundle = this.getIntent().getExtras();
		if (bundle.containsKey("deckId"))
			deckId = bundle.getInt("deckId");
		if (bundle.containsKey("cardId"))
			cardId = bundle.getInt("cardId");
		new loadDataBackground().execute();
		loadDataImage();
		btnBack.setOnClickListener(this);
		btnHelp.setOnClickListener(this);
	}

	void setFontTextView(TextView tv, String patch) {
		Typeface type = Typeface.createFromAsset(getAssets(), patch);
		tv.setTypeface(type);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack:
			finish();
			break;
		case R.id.btnHelp:
			onClickButtonHelp();
			break;
		default:
			break;
		}
	}

	public void onClickButtonHelp() {
		Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class);
		i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp);
		startActivityForResult(i, 0);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	private class loadDataBackground extends AsyncTask<Void, Void, Void> {
		String content = "";

		@Override
		protected Void doInBackground(Void... params) {
			content = loadContent(deckId, cardId);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			try {
				content = content.replaceAll("%", "&#37");
				
				String[] subContent = content.split("---");
				String header = subContent[0];
				String title = header.substring(0, header.indexOf('\n'));
				String title_jp = header.substring(content.indexOf('\n'),
						content.indexOf("---"));
				tv_title.setText(title);
				tv_title_jp.setText(title_jp);

				String temp_subContent1 = processContent(subContent[1]);
				String htmlText1 = "<html><body style=\"text-align:justify\">"
						+ "<font color='#0e3759'  font-size='14px' > "
						+ temp_subContent1 
						+ "</font>" + " </body></Html>";

				String temp_subContent2 = processContent(subContent[2]);
				String htmlText2 = "<html><body style=\"text-align:justify\">"
						+ "<font color='#0e3759'  font-size='14px' > "
						+ temp_subContent2 + "</font>" + " </body></Html>";
				
				tv_content1.loadDataWithBaseURL(null,
						String.format(htmlText1, temp_subContent1),
						"text/html", "utf-8", null);
				tv_content2.loadDataWithBaseURL(null,
						String.format(htmlText2, temp_subContent2),
						"text/html", "utf-8", null);

				if (subContent.length >= 4) {
					String temp_subContent3 = processContent(subContent[3]);
					String htmlText3 = "<html><body style=\"text-align:justify\">"
							+ "<font color='#0e3759'  font-size='14px' > "
							+ temp_subContent3 + "</font>" + " </body></html>";

					tv_content3.loadDataWithBaseURL(null,
							String.format(htmlText3, temp_subContent3),
							"text/html", "utf-8", null);
				}
			} catch (Exception e) {
				Utils.ELog("Substring errors",
						e == null ? "Errors occur when substring text of Card"
								: e.toString());
			}
			super.onPostExecute(result);
		}
	}

	// Thực hiện việc xử lý xâu kết quả
	private String processContent(String src) {
		String des = "";

		for (int i = 0; i < src.length() - 2; i++) {
			if ((src.charAt(i) == '○') && (src.charAt(i + 1) == ' ')) {
				des += src.charAt(i) + "";
				i += 2;
			} else if ((src.charAt(i) == '・') && (src.charAt(i + 1) == ' ')) {
				des += src.charAt(i) + "";
				i += 2;
			} else if ((src.charAt(i) == '→') && (src.charAt(i + 1) == ' ')) {
				des += src.charAt(i) + "";
				i += 2;
			}
			if (src.charAt(i) == '\n') {
				des += "<br>";
			} else
				des += src.charAt(i) + "";
		}

		return des;
	}

	public void loadDataImage() {
		String strDECKID = (deckId < 10) ? ("0" + deckId) : ("" + deckId);
		String strCARDID = (cardId < 10) ? ("0" + cardId) : ("" + cardId);
		String pathImageCard = ConstantValue.getPatchCardData(this) + "Card_"
				+ strDECKID + "/en_c" + strDECKID + strCARDID + ".png";
		String pathImageBackground = ConstantValue.getPatchCardData(this)
				+ "Card_" + strDECKID + "/en_bg" + strDECKID + ".jpg";
		iv_background.setPath(pathImageBackground);
		iv_card.setPath(pathImageCard);
		iv_background.loadImage(pathImageBackground);
		iv_card.loadImage(pathImageCard);
		// new ThreadLoadImage(this, handlerLoadImage, pathImageBackground,
		// iv_background, 1).start();
		// new ThreadLoadImage(this, handlerLoadImage, pathImageCard, null, 2)
		// .start();
	}

	// Handler handlerLoadImage = new Handler() {
	// public void handleMessage(android.os.Message msg) {
	// switch (msg.what) {
	// case 1:
	// if (msg.obj == null) {
	// iv_background.setImageResource(R.drawable.image_not_found);
	// return;
	// }
	// Drawable result1 = ((Drawable) msg.obj);
	// Bitmap bitmap1 = ((BitmapDrawable) result1).getBitmap();
	// if (!bitmap1.isRecycled())
	// iv_background.setImageBitmap(bitmap1);
	// break;
	// case 2:
	// if (msg.obj == null) {
	// iv_card.setImageResource(R.drawable.image_not_found);
	// return;
	// }
	// Drawable result = ((Drawable) msg.obj);
	// Bitmap bitmap = ((BitmapDrawable) result).getBitmap();
	// if (!bitmap.isRecycled())
	// iv_card.setImageBitmap(bitmap);
	// progress.setVisibility(View.INVISIBLE);
	// iv_card.setBackgroundResource(R.drawable.shadow_card_detail);
	// break;
	// default:
	// break;
	// }
	// };
	// };

	// Tra ve noi dung content ung voi cardId
	@SuppressWarnings("static-access")
	public String loadContent(int _deckId, int _cardId) {
		FileUtils fUtils = new FileUtils();
		String strDECKID = "";
		String strCARDID = "";
		String pathTextFile = "";
		String _content = "";
		byte[] bytes;
		InputStream is = null;
		BufferedReader bfReader = null;

		if (_deckId < 10)
			strDECKID = "0" + _deckId;
		else
			strDECKID = "" + _deckId;

		if (_cardId < 10)
			strCARDID = "0" + _cardId;
		else
			strCARDID = "" + _cardId;

		pathTextFile = ConstantValue.getPatchCardData(this) + "Card_"
				+ strDECKID + "/en_t" + strDECKID + strCARDID + ".txt";

		try {
			bytes = fUtils.decryptToByteArray(pathTextFile, "");
			_content = new String(bytes, "UTF-8"); // Va ma hoa ve utf-8

			// is = new ByteArrayInputStream(bytes);
			// bfReader = new BufferedReader(new InputStreamReader(is));
			// String str = "";
			// while ((str = bfReader.readLine()) != null) {
			// _content += str;
			// }

		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return _content;
	}

	// private void writeToFile(String data) {
	// try {
	// File file = new File(Environment.getExternalStorageDirectory()
	// + "/test.txt");
	// if (!file.exists()) {
	// file.createNewFile();
	// }
	// BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
	// buf.append(data);
	// buf.newLine();
	// buf.close();
	// } catch (IOException e) {
	// // TODO: handle exception
	// }
	// }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
	}
}
